package com.ourygo.fileselect.activity

import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.ImageView
import androidx.appcompat.app.AlertDialog
import com.bumptech.glide.Glide
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission.READ_EXTERNAL_STORAGE
import com.hjq.permissions.Permission.WRITE_EXTERNAL_STORAGE
import com.ourygo.fileselect.MainActivity
import com.ourygo.fileselect.R
import com.ourygo.fileselect.adapter.BookMarkAdapter
import com.ourygo.fileselect.base.BaseActivity
import com.ourygo.fileselect.bean.BookMark
import com.ourygo.fileselect.bean.Files
import com.ourygo.fileselect.databinding.PathSelectActivityBinding
import com.ourygo.fileselect.util.FileSelectUtil
import com.ourygo.fileselect.util.SharedPreferencesUtil
import com.ourygo.fileselect.util.Utils
import com.yuyh.library.imgsel.ISNav
import com.yuyh.library.imgsel.config.ISListConfig
import com.yuyh.library.imgsel.ui.ISListActivity
import java.io.File

class SplashActivity : BaseActivity() {
    private var picsNum = 0

    private lateinit var pathSelectAdapter: BookMarkAdapter
    private lateinit var data: MutableList<BookMark>

    private var typeArray: IntArray? = null

    private var fileSuffix: String? = null
    private var selectName: String? = null
    private var currentPath: String? = null
    private var selectNum = 0

    private lateinit var viewBinding: PathSelectActivityBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewBinding = PathSelectActivityBinding.inflate(layoutInflater)
        setContentView(viewBinding.root)

        requestPermissions(REQUEST_PERMISSION, object : OnPermissionCallback {
            override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                if (allGranted) {
                    initIntent()
                    setHorizontal()
                    initView()
                } else {
                    show("需要同意所有权限才能正常使用软件")
                    finish()
                }
            }

            override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                super.onDenied(permissions, doNotAskAgain)
                show("需要同意所有权限才能正常使用软件")
                finish()
            }
        })
    }

    private fun initIntent() {
        val intent = intent
        when (intent.action) {
            "ourygo.intent.action.OURYGO_FILE_SELECT" -> {
                typeArray = intent.getIntArrayExtra(FileSelectUtil.ARG_TYPE_ARRAY)
                fileSuffix = intent.getStringExtra(FileSelectUtil.ARG_FILE_SUFFIX)
                selectName = intent.getStringExtra(FileSelectUtil.ARG_SELECT_NAME)
                currentPath = intent.getStringExtra(FileSelectUtil.ARG_CURRENT_PATH)
                selectNum = intent.getIntExtra(FileSelectUtil.ARG_FILE_NUM, 1)

                if (typeArray == null) {
                    show("文件类型参数错误")
                    finish()
                    return
                }

                isHorizontal = intent.getBooleanExtra(FileSelectUtil.ARG_IS_HORIZONTAL, false)
                if (currentPath != null) {
                    startFileSelect(currentPath)
                    return
                }
            }

            "ourygo.intent.action.OURYGO_PICS_SELECT" -> {
                inItClass()
                picsNum = intent.getIntExtra(FileSelectUtil.ARG_PICS_NUM, 1)
                if (picsNum == 1) {
                    val ratioWidth = intent.getIntExtra(FileSelectUtil.ARG_PICS_RATIO_WIDTH, 0)
                    val ratioHeight = intent.getIntExtra(FileSelectUtil.ARG_PICS_RATIO_HEIGHT, 0)
                    val sizeWidth = intent.getIntExtra(FileSelectUtil.ARG_PICS_SIZE_WIDTH, 0)
                    val sizeHeight = intent.getIntExtra(FileSelectUtil.ARG_PICS_SIZE_HEIGHT, 0)
                    ISNav.getInstance().toListActivity(
                        this@SplashActivity,
                        getPicConfig(picsNum, ratioWidth, ratioHeight, sizeWidth, sizeHeight),
                        PICS_SELECT
                    )
                } else {
                    ISNav.getInstance()
                        .toListActivity(this@SplashActivity, getPicConfig(picsNum), PICS_SELECT)
                }
                return
            }
        }
    }

    private fun initView() {

        initData()

        pathSelectAdapter = BookMarkAdapter(this@SplashActivity, data)
        viewBinding.gvPathGrid.setAdapter(pathSelectAdapter)
        Utils.initToolbar(this, viewBinding.toolbar.toolbar, "路径选择", true)
        viewBinding.toolbar.toolbar.setNavigationOnClickListener { onBackPressed() }

        viewBinding.gvPathGrid.setOnItemClickListener { _: AdapterView<*>?, _: View?, p3: Int, _: Long ->
            val path = data[p3].path
            if (File(path).isDirectory) {
                startFileSelect(path)
            } else {
                Utils.show(this@SplashActivity, "该路径不存在")
            }
        }
        viewBinding.gvPathGrid.setOnItemLongClickListener { _: AdapterView<*>?, _: View?, position: Int, _: Long ->
            if (position <= 4) {
                Utils.show(this@SplashActivity, "该标签不能删除")
                return@setOnItemLongClickListener true
            }
            val dialog = AlertDialog.Builder(this@SplashActivity)
            dialog.setIcon(R.drawable.ic_launcher)
            dialog.setTitle("删除书签")
            dialog.setMessage("确定删除书签：" + data[position].name + "(" + data[position].path + ")")
            dialog.setNegativeButton("删除") { _: DialogInterface?, _: Int ->
                if (SharedPreferencesUtil.removeBookMark(
                        this@SplashActivity, data[position]
                    )
                ) {
                    Utils.show(this@SplashActivity, "删除成功")
                    data.removeAt(position)
                    pathSelectAdapter.notifyDataSetChanged()
                } else {
                    Utils.show(this@SplashActivity, "删除失败")
                }
            }
            dialog.setPositiveButton("取消") { _: DialogInterface?, _: Int -> }
            dialog.show().getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(Color.RED)
            true
        }

        viewBinding.tvStorage.setOnClickListener {
            startFileSelect(null)
        }
    }

    private fun initData() {
        data = SharedPreferencesUtil.getBookMarkList(this)

        data.add(
            0,
            BookMark.toBookMark(
                "QQ下载",
                Utils.PATH_GEN + "tencent/QQfile_recv/",
                R.drawable.ic_qq_download
            )
        )
        data.add(
            1,
            BookMark.toBookMark("系统下载", Utils.PATH_GEN + "Download/", R.drawable.ic_download)
        )
        data.add(2, BookMark.toBookMark("YGOMobile", Utils.PATH_MOBILE, R.drawable.ic_ygomobile))
        data.add(3, BookMark.toBookMark("YGO-OY", Utils.PATH_YGO_OY, R.drawable.ic_ygooy))
        data.add(4, BookMark.toBookMark("OURYGO", Utils.PATH_OURYGO, R.drawable.ic_ourygo))
    }

    private fun startFileSelect(currentPath: String?) {
        val intent1 = Intent(this@SplashActivity, MainActivity::class.java)
        intent1.putExtra(FileSelectUtil.ARG_TYPE_ARRAY, typeArray)
        intent1.putExtra(FileSelectUtil.ARG_FILE_SUFFIX, fileSuffix)
        intent1.putExtra(FileSelectUtil.ARG_SELECT_NAME, selectName)
        intent1.putExtra(FileSelectUtil.ARG_CURRENT_PATH, currentPath)
        intent1.putExtra(FileSelectUtil.ARG_FILE_NUM, selectNum)
        startActivityForResult(intent1, FILE_SELECT)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        // TODO: Implement this method
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == PICS_SELECT && resultCode == RESULT_OK && data != null) {
            val photos = data.getStringArrayListExtra(ISListActivity.INTENT_RESULT)
            val intent = Intent()
            intent.putExtra(FileSelectUtil.ARG_PICS, photos)
            setResult(RESULT_OK, intent)
        } else if (requestCode == FILE_SELECT && resultCode == RESULT_OK) {
            val intent = Intent()
            if (selectNum > 1) {
                intent.putExtra(
                    FileSelectUtil.ARG_PATH_LIST,
                    data!!.getStringArrayListExtra("PATH_LIST")
                )
            } else {
                val path = data!!.getStringExtra(FileSelectUtil.ARG_PATH)
                intent.putExtra(FileSelectUtil.ARG_PATH, path)
                intent.putExtra(
                    FileSelectUtil.ARG_FILE_TYPE,
                    data.getIntExtra(FileSelectUtil.ARG_FILE_TYPE, Files.FILE_TYPE_FILE)
                )
                val ls = ArrayList<String?>()
                ls.add(path)
                intent.putExtra(FileSelectUtil.ARG_PATH_LIST, ls)
            }
            setResult(RESULT_OK, intent)
        } else if (requestCode == FILE_SELECT && resultCode == RESULT_CANCELED) {
            return
        } else {
            val intent = Intent()
            intent.putExtra(FileSelectUtil.ARG_PICS, arrayOfNulls<String>(0))
            intent.putExtra(FileSelectUtil.ARG_PATH, "")
            setResult(RESULT_CANCELED, intent)
        }
        finish()
    }

    override fun onBackPressed() {
        val intent = Intent()
        intent.putExtra(FileSelectUtil.ARG_PICS, arrayOfNulls<String>(0))
        intent.putExtra(FileSelectUtil.ARG_PATH, "")
        setResult(RESULT_CANCELED, intent)
        Thread { Utils.clearImageCache(this@SplashActivity) }.start()
        super.onBackPressed()
    }

    private fun inItClass() {
        // 自定义图片加载器
        ISNav.getInstance().init { context: Context?, path: String?, imageView: ImageView? ->
            Glide.with(context!!).load(path).into(imageView!!)
        }
    }

    private fun getPicConfig(num: Int): ISListConfig {
        return getPicConfig(num, 0, 0, 0, 0)
    }

    private fun getPicConfig(
        num: Int,
        ratioWidth: Int,
        ratioHeight: Int,
        sizeWidth: Int,
        sizeHeight: Int
    ): ISListConfig {
        val dx = num > 1
        // 自由配置选项
        val config = ISListConfig.Builder() // 是否多选, 默认true
            .multiSelect(dx) // 是否记住上次选中记录, 仅当multiSelect为true的时候配置，默认为true
            .rememberSelected(false) // “确定”按钮背景色
            .btnBgColor(Utils.c(this, R.color.colorPrimary)) // “确定”按钮文字颜色
            .btnTextColor(Color.WHITE) // 使用沉浸式状态栏
            .statusBarColor(Utils.c(this, R.color.colorPrimary)) // 返回图标ResId
            .backResId(androidx.appcompat.R.drawable.abc_ic_ab_back_material) //.abc_ic_ab_back_mtrl_am_alpha)
            // 标题
            .title("图片选择") // 标题文字颜色
            .titleColor(Color.WHITE) // TitleBar背景色
            .titleBgColor(Utils.c(this, R.color.colorPrimary)) // 第一个是否显示相机，默认true
            .needCamera(false) // 最大选择图片数量，默认9
            .maxNum(num)
        if (ratioWidth > 0 && ratioHeight > 0 && sizeWidth > 0 && sizeHeight > 0) {
            config.needCrop(true)
                .cropSize(ratioWidth, ratioHeight, sizeWidth, sizeHeight)
        }
        return config.build()
    }


    companion object {
        private const val PICS_SELECT = 0
        private const val FILE_SELECT = 1

        private val REQUEST_PERMISSION = arrayOf(
            WRITE_EXTERNAL_STORAGE,
            READ_EXTERNAL_STORAGE,
        )
    }
}
